package com.aplink.generic;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;

import com.aplink.generic.network.GenericFile;
import com.aplink.generic.util.BitmapUtis;
import com.aplink.generic.util.Language;
import com.aplink.sg.R;

public class GenericCapturePhotoActivity extends Activity {
	private ImageView mImageView;
	private Button btnFinish;
	private Button btnEdit;
	private TextView tvDes;
	private LinearLayout mPanel;
	private static final int TAKE_PICTURE = 0;
	private static final int SELETE_GALLERY = 1;
	private static final int PIC_CROP = 2;

	private Uri mUri;
	private Bitmap mPhoto;
	private PopupMenu popupMenu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aplink__generic_capture_image);
		mPanel = (LinearLayout) findViewById(R.id.panel);
		tvDes = (TextView) findViewById(R.id.tv_des);
		mImageView = (ImageView) findViewById(R.id.img_photo);
		mImageView.setOnClickListener(mAddClickListener);
		btnFinish = (Button) findViewById(R.id.btnFinish);
		btnFinish.setOnClickListener(onFinishClickListener);
		btnEdit = (Button) findViewById(R.id.btnEdit);
		btnEdit.setOnClickListener(onEditClickListener);
		popupMenu = new PopupMenu(getApplicationContext(), btnEdit);
		popupMenu.getMenu().add(0, 0, 0, Language.getInstance().get("Crop"));
		popupMenu.getMenu().add(0, 1, 0,
				Language.getInstance().get("Rotate Right"));
		popupMenu.getMenu().add(0, 2, 0,
				Language.getInstance().get("Rotate Left"));
		popupMenu.getMenu().add(0, 3, 0, Language.getInstance().get("Reset"));
		popupMenu.setOnMenuItemClickListener(onMenuItemClickListener);

		tvDes.setTag(R.id.TEXT_ENGLISH, tvDes.getText().toString());
		tvDes.setText(Language.getInstance().get(
				tvDes.getTag(R.id.TEXT_ENGLISH).toString()));

		btnEdit.setTag(R.id.TEXT_ENGLISH, btnEdit.getText().toString());
		btnEdit.setText(Language.getInstance().get(
				btnEdit.getTag(R.id.TEXT_ENGLISH).toString()));

		btnFinish.setTag(R.id.TEXT_ENGLISH, btnFinish.getText().toString());
		btnFinish.setText(Language.getInstance().get(
				btnFinish.getTag(R.id.TEXT_ENGLISH).toString()));

		mImageView.performClick();
	}

	public Bitmap rotate(Bitmap b, int degrees, Matrix m) {
		if (degrees != 0 && b != null) {
			if (m == null) {
				m = new Matrix();
			}
			m.setRotate(degrees, (float) b.getWidth() / 2,
					(float) b.getHeight() / 2);
			Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
					b.getHeight(), m, true);
			if (b != null) {
				b.recycle();
				b = b2;
			}
		}
		return b;
	}

	private OnMenuItemClickListener onMenuItemClickListener = new OnMenuItemClickListener() {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			if (item.getItemId() == 1) {
				Matrix matrix = new Matrix();
				mPhoto = rotate(mPhoto, 90, matrix);
				mImageView.setImageBitmap(mPhoto);
			} else if (item.getItemId() == 2) {
				Matrix matrix = new Matrix();
				mPhoto = rotate(mPhoto, -90, matrix);
				mImageView.setImageBitmap(mPhoto);
			} else if (item.getItemId() == 0) {
				Intent cropIntent = new Intent("com.android.camera.action.CROP");
				cropIntent.setDataAndType(mUri, "image/*");
				cropIntent.putExtra("crop", "true");
				cropIntent.putExtra("aspectX", 1);
				cropIntent.putExtra("aspectY", 1);
				cropIntent.putExtra("outputX", 256);
				cropIntent.putExtra("outputY", 256);
				cropIntent.putExtra("return-data", true);
				startActivityForResult(cropIntent, PIC_CROP);
			} else if (item.getItemId() == 3) {
				getContentResolver().notifyChange(mUri, null);
				ContentResolver cr = getContentResolver();
				try {
					if (mPhoto != null) {
						mPhoto.recycle();
					}
					mPhoto = android.provider.MediaStore.Images.Media
							.getBitmap(cr, mUri);
					mImageView.setImageBitmap(mPhoto);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			return true;
		}
	};
	private View.OnClickListener onEditClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			popupMenu.show();
		}
	};
	private View.OnClickListener onFinishClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (mPhoto != null) {
				final GenericFile genericFile = BitmapUtis.getInstance()
						.savebitmap(
								GenericApplication.getInstance()
										.getCreatedTime(), mPhoto);
				Intent data = new Intent();
				Bundle bundle = new Bundle();
				bundle.putParcelable("bitmapFile", genericFile);
				data.putExtras(bundle);
				setResult(Activity.RESULT_OK, data);
			} else {
				setResult(Activity.RESULT_CANCELED);
			}
			finish();
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (mPhoto != null) {
				mPhoto.recycle();
			}
			switch (requestCode) {
			case TAKE_PICTURE:
				File f = new File(Environment.getExternalStorageDirectory(),
						"photo.jpg");
				mUri = Uri.fromFile(f);
				mPhoto = BitmapUtis.getInstance().decodeSampledBitmapFromFile(
						f.getPath(), 1400, 1200);
				mImageView.setImageBitmap(mPhoto);
				mPanel.setVisibility(View.VISIBLE);
				break;
			case SELETE_GALLERY: {
				mUri = data.getData();
				final String[] filePath = { MediaColumns.DATA };
				Cursor cursor = getContentResolver().query(mUri, filePath,
						null, null, null);
				cursor.moveToFirst();
				final String imagePath = cursor.getString(cursor
						.getColumnIndex(filePath[0]));
				mPhoto = BitmapUtis.getInstance().decodeSampledBitmapFromFile(
						imagePath, 1400, 1200);
				mImageView.setImageBitmap(mPhoto);
				mPanel.setVisibility(View.VISIBLE);
				break;
			}
			case PIC_CROP: {
				Bundle extras = data.getExtras();
				mPhoto = extras.getParcelable("data");
				mImageView.setImageBitmap(mPhoto);
				break;
			}
			}
		}
	}

	private DialogInterface.OnClickListener mClickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			if (which == 0) {
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				File f = new File(Environment.getExternalStorageDirectory(),
						"photo.jpg");
				i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
				mUri = Uri.fromFile(f);
				startActivityForResult(i, TAKE_PICTURE);
			} else if (which == 1) {
				final Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent, SELETE_GALLERY);
			}
		}

	};
	private View.OnClickListener mAddClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new Builder(
					GenericCapturePhotoActivity.this);
			builder.setTitle(Language.getInstance().get("Add Photo")).setItems(
					new String[] { Language.getInstance().get("Take a Photo"),
							Language.getInstance().get("Selete from gallery"),
							Language.getInstance().get("Close") },
					mClickListener);
			builder.create().show();
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mPhoto != null) {
			mImageView.setImageBitmap(null);
			mPhoto.recycle();
			mPhoto = null;
		}
	}

}
